package servlet;

import com.aliyun.oss.common.utils.StringUtils;
import dao.ProductDAO;
import entity.PageBean;
import entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author JPC
 * @version 1.0
 * @description: 商品浏览购买
 * @date 2024/7/15 22:28
 */
@WebServlet(name = "productSearch",value = "/product/search")
public class ProductSearchServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 接受分页参数pageNum pageSize;
        String num = req.getParameter("pageNum");
        String size = req.getParameter("pageSize");
        // 商品名称
        String name = req.getParameter("search");
        int pageNum = 1;
        int pageSize = 12;
        if(!StringUtils.isNullOrEmpty(num)){
            pageNum = Integer.parseInt(num);
        }
        if(!StringUtils.isNullOrEmpty(size)){
            pageSize = Integer.parseInt(size);
        }
        //2. 转化skip和limit
        int skip = (pageNum-1)*pageSize;
        int limit = pageSize;
        ProductDAO dao = new ProductDAO();
        Map<Long, List<Product>> map = dao.findPageByName(name,skip, limit);
        long total = map.keySet().iterator().next();
        List<Product> list = map.get(total);
        PageBean<Product> page = new PageBean<>();
        page.setTotal(total);
        page.setPageSize(pageSize);
        page.setPageNum(pageNum);
        page.setList(list);

        req.setAttribute("page",page);
        req.setAttribute("search",name);
        req.getRequestDispatcher("/product/Search.jsp").forward(req,resp);
    }
}
